/**
 * @Author: colpu
 * @Date: 2025-03-29 17:57:34
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-03-29 17:58:49
 * @
 * @Copyright (c) 2025 by colpu, All Rights Reserved.
 */
import Server from '@colpu/core';
const argv = process.argv;
const env = argv[2];
const {
  name,
  config = {},
  pkg = {}
} = new Server({
  env
});
const WORKSPACE = `/data/tmp/${name}`; // 本地构建临时目录
const PRODUCTION_DIR = `/data/project/${name}`; // 服务器 预发布/生产目录
const TEST_DIR = `/DataSSD/${name}`; // 服务器 local目录
const commonBash = [
  'pm2 save'
];
console.log(config)
// 构建环境变量
const enumEnv = {
  local: 'local',
  preview: 'preview',
  production: 'production'
};

export default function (shipit) {
  require('shipit-deploy')(shipit);
  const branch = config.deploy.branch || 'master';
  shipit.initConfig({
    production: {
      servers: config.deploy.servers,
      deployTo: WORKSPACE,
      branch
    },
    preview: {
      servers: config.deploy.servers,
      deployTo: WORKSPACE,
      branch
    },
    local: {
      servers: config.deploy.servers,
      deployTo: WORKSPACE,
      branch
    },
    default: {
      workspace: WORKSPACE, // 本地的临时工作目录
      repositoryUrl: pkg.repository.url,
      ignores: ['.git', 'node_modules'],
      keepReleases: 2,
      shallowClone: false,
      deleteOnRollback: false
    }
  });

  // 1、创建本地临时目录
  shipit.on('init', () => {
    return shipit.local(`mkdir -p ${WORKSPACE}`);
  });

  // 2、仓库拉取完成，执行代码构建和资源发布（上传阿里oss）
  shipit.on('fetched', function () {
    shipit.start(['build']);
  });

  // 3、发布完成，执行构建pm2服务启动
  shipit.on('published', function () {
    const env = shipit.options.environment;
    const options = {
      workspace: WORKSPACE,
      dir: env === enumEnv.local ? TEST_DIR : PRODUCTION_DIR,
      env
    };
    const command = generateRemoteCmd(options);
    return shipit.remote(command);
  });

  // 自定义事件进行项目build
  shipit.blTask('build', function () {
    const command = [
      `cd ${WORKSPACE}`,
      `yarn install --no-lockfile`
    ].join(' && ');
    return shipit.local(command);
  });
}

// cmd远程命令生成
function generateRemoteCmd(options) {
  const { workspace, dir, env } = options;
  return [
    `mkdir -p ${dir}`,
    `cp -rf ${workspace}/current/. ${dir}`,
    `cd ${dir}`,
    `yarn install --no-lockfile --production`,
    `(pm2 delete ${name} || echo)`,
    `npm run ${env}`
  ].concat(commonBash).filter((cmd) => cmd).join(' && ');
}
